import request from '@/utils/request'

export const getChannelAction = (payload) => {
  // 获取频道
  return async (dispatch, getState) => {
    const {
      data: { channels },
    } = await request.get('/channels')
    dispatch({ type: 'article/channel', list: channels })
  }
}

// 根据过滤条件获取文章列表
export const getArticleAction = (payload) => {
  return async (dispatch, getState) => {
    const {
      data: { page, per_page, results, total_count },
    } = await request.get('/mp/articles', {
      params: payload,
    })
    const datas = {
      page,
      pageSize: per_page,
      list: results.map((item) => ({
        ...item,
        cover: item.cover.images[0],
      })),
      total: total_count,
    }
    dispatch({ type: 'article/list', datas })
  }
}

// 删除文章
export const delArticleAction = (id, filters) => {
  return async (dispatch, getState) => {
    await request.delete(`/mp/articles/${id}`)
    dispatch(getArticleAction(filters))
  }
}

// 新增文章
export const addArticleAction = (data, isDraft, isEdit) => {
  return async (dispatch, getState) => {
    if (isEdit) {
      await request.put(`/mp/articles/${data.id}?draft=${isDraft}`, data)
    } else {
      await request.post(`/mp/articles?draft=${isDraft}`, data)
    }
  }
}
